package peer.gui;

import java.util.ArrayList;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

public class ChunkListModel implements TableModel
{
	ArrayList<ChunkModel> data = new ArrayList<ChunkModel>();
	String[] columnNames = {"Chunk #", "Size", "Have?", "Blocks", "Completed", "% Completed"};
	Class[] columnClasses = {Integer.class, Integer.class, Boolean.class, Integer.class, Integer.class, Double.class};
	
	TableModelListener listener;
	
	final static int BLOCK_SIZE = 16384;

	public void addTableModelListener(TableModelListener l)
	{
		listener = l;
	}

	public Class<?> getColumnClass(int columnIndex)
	{
		return columnClasses[columnIndex];
	}

	public int getColumnCount()
	{
		return columnNames.length;
	}

	public String getColumnName(int columnIndex)
	{
		return columnNames[columnIndex];
	}

	public int getRowCount()
	{
		return data.size();
	}

	public Object getValueAt(int rowIndex, int columnIndex)
	{
		switch (columnIndex)
		{
		case 0:
			return data.get(rowIndex).number;
		case 1:
			return data.get(rowIndex).size;
		case 2:
			return data.get(rowIndex).have;
		case 3:
			return data.get(rowIndex).blocks;
		case 4:
			return data.get(rowIndex).blocksCompleted;
		case 5:
			return data.get(rowIndex).percentCompleted;
		}
		return null;
	}

	public boolean isCellEditable(int rowIndex, int columnIndex)
	{
		return false;
	}

	public void removeTableModelListener(TableModelListener l)
	{
		listener = null;
	}

	public void setValueAt(Object aValue, int rowIndex, int columnIndex)
	{
	}

	public class ChunkModel
	{
		int number;
		int size;
		boolean have;
		int blocks;
		int blocksCompleted;
		double percentCompleted;
		//TODO: have number of copies of this chunk on the network
		//TODO: speed
		
		public ChunkModel(int number, int size, boolean have, int blocksCompleted)
		{
			this.number = number;
			this.size = size;
			this.have = have;
			this.blocks = size / BLOCK_SIZE;
			this.blocksCompleted = blocksCompleted;
			this.percentCompleted = (double) blocks / blocksCompleted;
		}
	}

	public void clear()
	{
		data.clear();
		listener.tableChanged(new TableModelEvent(this));
	}

	public void addChunk(int count, int chunkSize)
	{
		data.add(new ChunkModel(count, chunkSize, false, 0));
	}

	public void completedBlock(int block)
	{
		int inChunk = (BLOCK_SIZE * block) / data.get(0).size;
		ChunkModel c = data.get(inChunk);
		c.blocksCompleted++;
		c.percentCompleted = 100 * c.blocksCompleted / c.blocks; 
		if(c.blocksCompleted == c.blocks)
		{
			c.have = true;
		}
		listener.tableChanged(new TableModelEvent(this, inChunk));
	}
}
